package util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtil {
    public static String uploadFile(HttpServletRequest req, Part part) {
        //获取文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("文件名："+fileName);
        //防止文件名重复
        fileName = UUID.randomUUID().toString().replace("-","") + "_" +fileName;
        //设置文件上传路径
        String fileUploadUrl = req.getServletContext().getRealPath("/upload");
        System.out.println("指定上传路径:"+fileUploadUrl);
        //file流判断文件夹是否存在
        File file = new File(fileUploadUrl);
        //判断上传路径是否存在，不存在新建路径
        if (!file.exists()) {
            file.mkdir();
        }
        //将文件保存到指定目录
        try {
            part.write(fileUploadUrl+ "/" + fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String imgUrl = "/upload/"+fileName;
        System.out.println("文件上传成功，上传地址在"+imgUrl);
        return imgUrl;
    }
}
